package com.example.javabasic.thread.classtwo.singleton.demo2;

import java.util.stream.IntStream;

//线程等待集合
public class WaitSet {
    //所有的对象都有一个waitset   用来存放调用了该对象wait方法后进入block状态的线程
    //线程被notify后  不一定立即执行
    private static final Object LOCK = new Object();
    public static void main(String[] args) {
        //创建10个线程 并且都进入wait状态
        IntStream.range(0,10).forEach(n->{
            new Thread(String.valueOf(n)){
                @Override
                public void run() {
                    synchronized (LOCK){
                        try {
                            System.out.println(Thread.currentThread().getName()+" 即将进入等待");
                            //wait 会将当前线程放入锁对象的waitset中, 并且放弃synchronized 锁,
                            LOCK.wait();
                            System.out.println(Thread.currentThread().getName()+" 已经唤醒");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        });

        //休眠2秒
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        IntStream.range(0,10).forEach(i->{
            synchronized (LOCK){
                //唤醒线程,随机唤醒一个
                LOCK.notify();
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
